package com.studyv3.test.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.studyv3.common.core.domain.PageBean;
import com.studyv3.common.core.domain.R;
import com.studyv3.test.domain.Resource;
import com.studyv3.test.mapper.ResourceMapper;
import com.studyv3.test.minio.MinioUtil;
import com.studyv3.test.service.ResourceService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
* @author 侯杰
* @description 针对表【res_resource(对象存储表)】的数据库操作Service实现
* @createDate 2024-04-28 10:44:26
*/
@Service
@RequiredArgsConstructor
public class ResourceServiceImpl
    implements ResourceService {

    private final ResourceMapper resourceMapper;
    private final MinioUtil minioUtil;


    @Override
    public R uploadImg(MultipartFile file) throws IOException {
        String url=upload(file,"图片");
        return url==null?R.fail("亲，上传资源失败！"): R.ok(url);
    }

    private String upload(MultipartFile file,String type) throws IOException {
        //1.验证
        if(file.isEmpty()){
            return null;
        }
        //2.文件名 对象名 唯一 限制长度
        String objName=file.getOriginalFilename();
        //限制长度和重命名
        if(objName.length()>30){
            objName=objName.substring(objName.length()-30);
        }
        objName=System.currentTimeMillis()+"_"+objName;

        //3.上传 Minio
        String url=minioUtil.putObject(minioUtil.bucket,objName,file.getInputStream());
        if(StringUtils.hasLength(url)){
            //4.上传成功 操作数据库
            resourceMapper.insert(new Resource(file.getSize(),minioUtil.bucket,objName,type,url));

        }
        return url;
    }

}




